package com.cd.questionBank.controller;

import com.cd.questionBank.util.DomainCache;
import com.cd.questionBank.util.LocalDomainDto;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/lockT")
public class LockController {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LockController.class);

    //构想 一个同步接口 一个返回map的接口 同步时不能返回map

    //同步数据接口
    @RequestMapping("/update")
    public String sync(@RequestParam(value = "force",defaultValue = "false") boolean force,
            @RequestBody List<String> list){

        logger.info("强制刷新模式:{}",force);
        if(!DomainCache.getInstance().isAvailable() || force) {
            List<LocalDomainDto> lists = convertToLocalDomainDto(list);
            String result = DomainCache.getInstance().refresh(lists);
            logger.info("标准缓存数据刷新成功");
            return result;
        }
        return "数据可用，无需刷新";
    }

    //获取列表
    @RequestMapping("/get")
    public Map<String, String> get(){
        logger.info("获取数据");
        Map<String, String> all = DomainCache.getInstance().getAll();
        logger.info("获取数据成功");
        return all;
    }

    private List<LocalDomainDto> convertToLocalDomainDto(List<String> list) {
        List<LocalDomainDto> lists=new ArrayList<>();
        //list "id,code,enum" 用于转换输入和输出
        for (String s : list) {
            String[] sa=s.split(",");
            LocalDomainDto dto=new LocalDomainDto();
            dto.setId(sa[0]);
            dto.setDomainCode(sa[1]);
            dto.setReferenceCode(sa[2]);
            lists.add(dto);
        }
        return lists;
    }
}
